<?php
include($_SERVER["DOCUMENT_ROOT"] . "/bob.php");
include("fonctions_forum.php");
require ($_SERVER["DOCUMENT_ROOT"] . "/lib/simple_html_dom.php");
$mysqli = new_mysqli($host, $user, $password, $database); //connection à la DB

$idtopic = get_num($_GET['id']);

$current_topic = get_line_in_db($mysqli, "forum_topics", "topic_id", $idtopic);
if ($current_topic == NULL) {
    header("Location: /");
    exit();
}
//Si le topic était dans les nouveaux, on l'en enlève.
if (isset($_SESSION['new_topics']) && isset($_SESSION['new_topics']['topic_' . $idtopic]))
    unset($_SESSION['new_topics']['topic_' . $idtopic]);

//Droits d'accès
$current_forum = get_line_in_db($mysqli, "forums", "forum_id", $current_topic['forum_id']);
if ($current_forum['auth_view'] == '2' && @$_SESSION['grad'] != "admin") {
    $result = mysqli_query_with_error($mysqli, "SELECT forum_id FROM forum_private WHERE forum_id ='{$current_forum['forum_id']}' AND user_id='{$_SESSION['id']}' LIMIT 1");
    if ($result->num_rows == 0) {
        header("Location: /");
        exit();
    }
}
//Mise à jour du nombre de vues
mysqli_query_with_error($mysqli, "UPDATE forum_topics SET topic_views = topic_views + 1 WHERE topic_id='$idtopic'");

// Sécurité contre le piratage
if ((@$_GET['mod'] == "verrouill" || @$_GET['mod'] == "deverrouill" || @$_POST['bouton'] == "Deplacer" || @$_GET['mod'] == "supr" || @$_GET['mod'] == "totalsupr" || @$_GET['mod'] == "cut" || @$_POST['choivot'] != "") && $_GET['idefix'] != md5(session_id() . $_SESSION['id'])) {
    echo "<p align='center'>Il semblerai que vous ayez été victime d'une tentative de piratage. 
La page où vous étiez précédemment a été créée pour détourner votre session.</p>";
    exit;
}

if (isset($_POST['reponse_vote']) && $_POST['reponse_vote'] != "") { //On répond à un sondage
    $choivo = get_num($_POST['reponse_vote']);
    $resultsy = mysqli_query_with_error($mysqli, "SELECT topic_id FROM forum_sondage_voters WHERE topic_id='$idtopic' AND vote_user_id='{$_SESSION['id']}' LIMIT 1");
    if ($resultsy->num_rows == 0)  //Si l'utilisateur n'a pas déjà voté.
        mysqli_query_with_error($mysqli, "INSERT INTO forum_sondage_voters(topic_id, vote_user_id, vote_user_ip, vote_option_id) VALUES('" . $idtopic . "', '" . $_SESSION['id'] . "', '" . $_SERVER['REMOTE_ADDR'] . "', '" . $choivo . "')");
    else
        mysqli_query_with_error($mysqli, "UPDATE forum_sondage_voters SET vote_user_ip = '" . $_SERVER['REMOTE_ADDR'] . "', vote_option_id = '" . $choivo . "' WHERE topic_id='" . $idtopic . "' AND vote_user_id='" . $_SESSION['id'] . "'");
}

//Est-on moderateur ici ?
$is_modo = ((isset($_SESSION['grad']) && $_SESSION['grad'] == "admin") || is_moderateur($mysqli, $_SESSION['id'], $current_forum['forum_id']));
        

if ($is_modo && @$_GET['mod'] == "verrouill")//verouillage du topic
    mysqli_query_with_error($mysqli, "UPDATE forum_topics SET topic_status='1' WHERE topic_id='$idtopic'");
if ($is_modo && @$_GET['mod'] == "deverrouill")//deverouillage du topic
    mysqli_query_with_error($mysqli, "UPDATE forum_topics SET topic_status='0' WHERE topic_id='$idtopic'");

if (@$_POST['bouton'] == "Deplacer") { //deplacement du topic
    if (@$_POST['traceur'] == '1') {
        mysqli_query_with_error($mysqli, "INSERT INTO forum_topics(topic_title, forum_id, topic_time, topic_moved_id) VALUES
		('{$current_topic['topic_title']}', '{$current_topic['forum_id']}', '{$current_topic['topic_time']}', '$idtopic')");
    }
    $futur_forum = get_num($_POST['dfrum']);
    mysqli_multi_query_with_error($mysqli, "UPDATE forum_topics SET forum_id='$futur_forum' WHERE topic_id='$idtopic'; UPDATE forum_posts SET forum_id='$futur_forum' WHERE topic_id='$idtopic'");
    $current_forum = get_line_in_db($mysqli, "forums", "forum_id", $futur_forum);
}

if ($is_modo && @$_GET['mod'] == "supr")
    atomiserpost($mysqli, $_GET['idp'], $idtopic); //cas de suppression

if ($is_modo && @$_GET['mod'] == "totalsupr") { //cas de suppression totale!!!
    $result = mysqli_query_with_error($mysqli, "SELECT * FROM forum_posts WHERE topic_id='$idtopic'");
    while ($ligne = $result->fetch_assoc())
        atomiserpost($mysqli, $ligne['post_id'], $idtopic);
}

if ($is_modo && @$_GET['mod'] == "cut") { //cas de découpe
    $result = mysqli_query_with_error($mysqli, "SELECT * FROM forum_posts WHERE topic_id='$idtopic' AND post_time > " . get_num($_GET['ptime']));
    while ($ligne = $result->fetch_assoc())
        atomiserpost($mysqli, $ligne['post_id'], $idtopic);
}

$current_topic = get_line_in_db($mysqli, "forum_topics", "topic_id", $idtopic); //Mise à jour du topic

function atomiserpost($mysqli, $idpost, $idtopic) { //TODO mieux commenter et alleger à mort les aller-retour ac la DB
    $result = mysqli_query_with_error($mysqli, "SELECT * FROM forum_posts WHERE post_id='$idpost' LIMIT 1");
    if ($result->num_rows > 0) {
        $current_post = $result->fetch_assoc();
        $idauteur = $current_post['poster_id'];
        mysqli_multi_query_with_error($mysqli, "DELETE FROM forum_posts WHERE post_id='$idpost'; UPDATE gens SET user_posts = user_posts - 1 WHERE user_id='$idauteur';");
        if (get_data_in_db($mysqli, "forum_topics", "topic_id", $idtopic, "topic_time") == $current_post['post_time']) {
            $result2 = mysqli_query_with_error($mysqli, "SELECT post_time FROM forum_posts WHERE topic_id='$idtopic' ORDER BY post_id DESC LIMIT 1");
            $dpost2 = $result2->fetch_assoc();
            mysqli_query_with_error($mysqli, "UPDATE forum_topics SET topic_time='{$dpost2['post_time']}' WHERE topic_id='$idtopic'");
        }
        if (get_line_numbers($mysqli, "forum_posts", "topic_id", $idtopic) == "0") //C'était le dernier post du topic.
            atomisertopic($mysqli, $idtopic);
    }
}

function atomisertopic($mysqli, $idtopic) {
    delete_sondage($mysqli, $idtopic);
    $idforum = get_data_in_db($mysqli, "forum_topics", "topic_id", $idtopic, "forum_id"); //TODO le passer plutot qu'aller le chercher.
    mysqli_query_with_error($mysqli, "DELETE FROM forum_topics WHERE topic_id='$idtopic' OR topic_moved_id='$idtopic'");
    header("Location: forum.php?id=$idforum");
    exit();
}

function affiche_repondre($mysqli, $current_forum, $current_topic) {
    echo '<ul class="actions ombre">';


    if ($current_forum['forum_status'] != '1' && $current_topic['topic_status'] != '1') {
        $suivi = mysqli_query($mysqli, "SELECT * FROM forum_topics_suivis WHERE topic_id=" . $current_topic['topic_id'] . " AND user_id=" . $_SESSION['id']);
        if ($suivi->num_rows > 0) {
            echo '<li class="btn ombre"><a id="btn_suivre_topic" href="javascript:suivre_topic(false)">Ne plus suivre la discussion</a></li>';
        } else {
            echo '<li class="btn ombre"><a id="btn_suivre_topic" href="javascript:suivre_topic(true)">Suivre la discussion</a></li>';
        }
        echo '<li class="btn ombre"><a href="topic.php?id=' . $current_topic['topic_id'] . '&page=derniere#reponse_rapide">Répondre</a></li>';
    } else {
        echo '<li class="btn ombre"><a>Verrouillé</a></li>';
    }
}

entete($mysqli, $current_topic['topic_title']);
?>
<script>

    function getXMLHttpRequestObject() {
        var ref = null;
        if (window.XMLHttpRequest) {
            ref = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // Older IE.
            ref = new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        return ref;
    }

    function citerMessage(postid, poster) {
        $.get("ajax/cherche_message.php", {post_id: postid}, function(data) {
            var message = "[quote=\"" + poster + "\"]" + data + "[/quote]";
            $("textarea#wysiwyg").val(message);
            var aTag = $("a[name='reponse_rapide']");
            $('html,body').animate({scrollTop: (aTag.offset().top) - 130}, 'slow', function() {
                $("textarea#wysiwyg").focus();
            });
        });

    }

    function suivre_topic(val) {
        var action;
        if (val === true) {
            $("#btn_suivre_topic").attr("href", "javascript:suivre_topic(false)");
            $("#btn_suivre_topic").text("Ne plus suivre la discussion");
            action = "add";
        } else {
            $("#btn_suivre_topic").attr("href", "javascript:suivre_topic(true)");
            $("#btn_suivre_topic").text("Suivre la discussion");
            action = "delete";
        }
        $.get("ajax/suivre_topic.php", {etat: action, topic_id: <?php echo $idtopic ?>}, function(data) {
            if (data !== "OK") {
                alert('Une erreur s\'est produite. Veuillez réessayer ultérieurement. ' + data);
            }
        });
    }



</script>
<?php
if (isset($_SESSION['id'])){
    $verif_idef = "idefix=" . md5(session_id() . $_SESSION['id']) . "&";

if ($is_modo && isset($_GET['mod']) && $_GET['mod'] == "deplac") { //Cas d'une demande de déplacement du topic
    echo"<div style='margin:50px; border: 2px ridge #555555; text-align:center;'><br><form action='topic.php?" . $verif_idef . "id=$idtopic' method='post'>
	Deplacer vers: <select name='dfrum'>";
    $result = mysqli_query_with_error($mysqli, "SELECT * FROM forums ORDER BY forum_order");
    while ($ligne = $result->fetch_assoc())
        echo"<option value='{$ligne['forum_id']}'>{$ligne['forum_name']}";
    echo"</select><br><br><input type='checkbox' name='traceur' value='1'>Laisser un sujet-traceur sur l'ancien forum<br>
	<br><input type='submit' value='Deplacer' name='bouton'></form></div>";
    exit;
}
}
$sujet = get_data_propre_sortie_db($current_topic['topic_title']);
$is_deplac = "";
if ($current_topic['topic_sondage'] != "") {
    $is_deplac = $is_deplac . "[Sondage] ";
}
$nom_forum = get_data_propre_sortie_db($current_forum['forum_name']);
echo '<h4 class="ombre"><a href="forum.php?id=' . $current_topic['forum_id'] . '">' . $nom_forum . '</a> <span class="bleuf">:::</span> ' . $is_deplac . $sujet . '</h4>';

$nb_message_par_page = 10;
$retour_total = mysqli_query_with_error($mysqli, "SELECT COUNT(*) AS total FROM forum_posts WHERE topic_id=" . $idtopic);
$donnees_total = $retour_total->fetch_assoc();
$total = $donnees_total['total'];

$nombreDePages = ceil($total / $nb_message_par_page);
if (isset($_GET['m'])) {



    $lignes = mysqli_query_with_error($mysqli, "SELECT post_id FROM forum_posts WHERE topic_id=" . $idtopic);
    $num = 0;
    $trouve = false;
    while ($trouve == false && $ligne = $lignes->fetch_assoc()) {
        $num++;
        if ($_GET['m'] == $ligne['post_id']) {
            $trouve = false;
        }
    }
    if ($num <= $total) {
        $page = $nombreDePages;
    } else {
        $page = ($num % $nombreDePages) + 1;
    }
} elseif (isset($_GET['page'])) {
    $page = $_GET['page'];
    if ($page == 'derniere') {
        $page = $nombreDePages;
    }
} else {
    $page = 1;
}
$pageActuelle = intval($page);
if ($pageActuelle > $nombreDePages) {
    $pageActuelle = $nombreDePages;
}
$premiereEntree = ($pageActuelle - 1) * $nb_message_par_page;

$result_posts = mysqli_query_with_error($mysqli, "SELECT * FROM forum_posts WHERE topic_id='$idtopic' ORDER BY post_id LIMIT " . $premiereEntree . "," . $nb_message_par_page);  //recherche des posts concernés
//$data_pages = pagination(20, $result_posts->num_rows, "topic.php?id=$idtopic");
//if($data_pages == NULL){
//	header("Location: /"); exit();}
if (isset($_SESSION['id'])){
affiche_repondre($mysqli, $current_forum, $current_topic);
}
//Pagination - Initialisation


if ($nombreDePages > 1) {
    echo '<li class="select droit">
                    <label for="page">Aller à la page</label>
                    <div class="style_select">
                    <select name="select" onchange="document.location.href=(\'topic.php?id=' . $idtopic . '&page=\'+document.getElementById(\'page\'))" id="page" name="select">';

    //<select id="page" onchange="javascript:document.location.href=\'topic.php?id='.$idtopic.'&page=\'+document.getElementbyId(\'page\').value" name="select">';
    for ($i = 1; $i <= $nombreDePages; $i++) {
        $selected = "";
        if ($pageActuelle == $i) {
            $selected = 'selected="selected"';
        }
        echo '<option value="' . $i . '" ' . $selected . '>' . $i . '</option>';
    }
    echo '</select></div></li>';
}
echo '</ul>';

echo '<div id="sujet" class="ombre">';
if ($current_topic['topic_sondage'] != "") { //sondage éventuel
    echo '<div class="separator"></div>';
    echo '<div class="post">';

    $choix = -1;
    if (empty($_SESSION['login'])){
        //echo "<p>Veuillez vous connecter pour voter</p>";
        echo '<form class="sondage" action="aaaaaaaa.php" method="post">';
    }else {
        $result = mysqli_query_with_error($mysqli, "SELECT topic_id, vote_option_id FROM forum_sondage_voters WHERE topic_id='$idtopic' AND  vote_user_id='{$_SESSION['id']}' LIMIT 1");
        if ($result->num_rows > 0) {
            $voote = $result->fetch_assoc();
            $choix = $voote['vote_option_id'];
            echo "<br/><p style='text-align:center;font-weight:bold'>Vous avez déjà voté, mais vous pouvez changer votre choix</p>";
        }
        echo '<form class="sondage" action="topic.php?' . $verif_idef . 'id=' . $idtopic . '" method="post">';
    }
    
    $nbresult = get_line_numbers($mysqli, "forum_sondage_voters", "topic_id", $idtopic);
    echo '<div class="entete">';
    echo '<h5>' . $current_topic['topic_sondage'] . '</h5>';
    echo '<p>Total des votes : ' . $nbresult . '</p>';
    echo '</div>';

    echo '<div class="reponses">';


    $result = mysqli_query_with_error($mysqli, "SELECT * FROM forum_sondage_result WHERE topic_id='$idtopic'");
    $result_sondage = array();


    while ($lign = $result->fetch_assoc()) {

        $nb_reponse = get_line_numbers($mysqli, "forum_sondage_voters", "vote_option_id", $lign['vote_option_id']);
        if ($nbresult == '0') {
            $pourc = 0;
        } else {
            $pourc = round(($nb_reponse / $nbresult) * 100, 1);
        }
        $long = $pourc * 2 + 2;
        $result_sondage[] = array($lign['vote_option_id'], $lign['vote_option_text'], $pourc, $nb_reponse);
    }
    // var_dump($result_sondage);
    echo '<div class="colonne gauche">';
    for ($i = 0; $i < count($result_sondage); $i++) {
        $check = "";

        if ($result_sondage[$i][0] == $choix) {
            $check = "checked";
        }
        if (!empty($_SESSION['login'])) {
            // echo $result_sondage[$i][1];
            echo '<input type="radio" name="reponse_vote" value="' . $result_sondage[$i][0] . '" id="reponse' . $result_sondage[$i][0] . '" class="input_reponse" ' . $check . ' /><label for="reponse' . $result_sondage[$i][0] . '">' . $result_sondage[$i][1] . '</label><br/>';
        } else {
            echo '<label>'.$result_sondage[$i][1] . '</label><br/>';
        }
    }
    echo '</div>';
    echo '<div class="colonne droite">';
    for ($i = 0; $i < count($result_sondage); $i++) {
        echo '<div id="reponse' . $result_sondage[$i][0] . '" class="reponse">';
        echo '<div style="width:' . $result_sondage[$i][2] . '%"></div>';
        echo '</div>';
        echo '<p>' . $result_sondage[$i][2] . '%<span class="bleu">:: ' . $result_sondage[$i][3] . ' vote' . ((get_num($result_sondage[$i][3]) > 1) ? 's' : '') . '</span></p><br/>';
    }
    echo '</div>';
    echo '</div>';


    if (!empty($_SESSION['login'])) {
        echo '<ul class="actions">';
        echo '<li class="btn ombre"><input type="submit" value="Voter"></li>';
        echo '</ul>';
        echo '</form>';
    }
    echo '</div>';
}


$nb_current = display_posts($mysqli, $result_posts, $idtopic, $pageActuelle, null, $is_modo);
echo '</div>';


//echo"<a class='btn ombre' href='#'>Revenir en haut de page</a><br>";
pagination_bas('topic.php?id=' . $idtopic, '&page=', $nombreDePages, $page);
if (isset($_SESSION['id'])){
echo '<a name="reponse_rapide" />';
echo '<h4 class="ombre"><a href="forum.php?id=' . $current_topic['forum_id'] . '">' . $nom_forum . '</a> <span class="bleuf">:::</span> ' . $is_deplac . $sujet . '</h4>';
if ($page == $nombreDePages) {

    echo '<h4 class="reponse">Répondre</h4>';
    javascript_BBcode();
    echo '<form id="rep_rapide" class="post ombre" action="post.php" method="POST" name="formul">';

    echo "<input type='hidden' name='topic' value='" . $idtopic . "' />";
    echo "<input type='hidden' name='frum' value='" . $current_topic['forum_id'] . "' />";
    echo "<input type='hidden' name='page' value='" . $page . "' />";
    echo "<input type='hidden' name='login' value='" . $_SESSION['login'] . "' />";
    echo "<input type='hidden' name='idefix' value='" . md5(session_id() . $_SESSION['id']) . "' />";
    if (isset($_GET['citation'])) {
        $rqt_message = "SELECT post_text FROM forum_posts WHERE post_id=" . $_GET['citation'];
        $result = mysqli_query_with_error($mysqli, $rqt_message);
        $ligne = $result->fetch_assoc();
        $messa = "[quote=\"" . urldecode($_GET['poster']) . "\"]" . $ligne['post_text'] . "[/quote]";
    } else {
        $messa = "";
    }

    display_post_message(1, 1, $messa, $mysqli);

    echo '<ul class="actions">';
    //!Aecho '<li><input type="checkbox" name="auto" value="auto" name="nsmil" id="smiley_off"><label for="smiley_off">Désactiver les smileys</label></li>';
    echo '<li class="btn ombre droit"><input type="submit" value="Envoyer"></li>';
//echo '<li class="btn ombre droit"><input type="submit" value="Prévisualiser"></li>';
    echo '</ul>';

    echo '</form>';
} else {
    echo '<ul class="actions">';
    if ($current_forum['forum_status'] != '1' && $current_topic['topic_status'] != '1') {
        echo '<li class="btn ombre"><a href="topic.php?id=' . $current_topic['topic_id'] . '&page=derniere#reponse_rapide">Répondre</a></li>';
    } else {
        echo '<li class="btn ombre"><a>Verrouillé</a></li>';
    }
    echo '</ul>';
}
if ($is_modo) {
    echo"<p align='center'><br><br>";
    if ($current_topic['topic_status'] == '1')
        echo"<a href='topic.php?" . $verif_idef . "id=$idtopic&mod=deverrouill'><img src='images/topic_unlock.gif' border='0'></a> ";
    else
        echo"<a href='topic.php?" . $verif_idef . "id=$idtopic&mod=verrouill'><img src='images/topic_lock.gif' border='0'></a> ";
    echo "<a href='topic.php?id=$idtopic&mod=deplac'><img src='images/topic_move.gif' border='0'></a> 
<a href='topic.php?" . $verif_idef . "id=$idtopic&mod=totalsupr' onclick='return confirm(\"Veux-tu vraiment atomiser ce topic innocent? (entièrement?)\");'>
<img src='images/topic_delete.gif' border='0'></a></p>";
}
}
?>

</div> <!-- fin div contenu-->
</div> <!-- fin div corps-->

<?php
if (isset($_GET['m'])) {
    ?>
    <script>
        var aTag = $("a[name='<?php echo $_GET['m'] ?>']");
        $('html,body').animate({scrollTop: (aTag.offset().top) - 130}, 'slow');
    </script>
    <?php
}
show_footer();
?>
